package com.rzico.sbl.ui.member

import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityMemberRecordBinding
import com.rzico.sbl.model.OrderFooter
import com.rzico.sbl.model.OrderGoods
import com.rzico.sbl.model.OrderHeader
import com.rzico.sbl.other.*
import com.rzico.sbl.ui.order.OrderDetailActivity
import com.rzico.sbl.viewmodel.MemberViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common_ui.base.*
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.showTimeRangeDialog
import com.xinnuo.slimadapter.SlimAdapter

class MemberRecordActivity : BaseActivity(R.layout.activity_member_record) {

    private val mBinding by lazy { ActivityMemberRecordBinding.bind(getRootView()) }

    private lateinit var mDateMode: String
    private var mBeginDate = ""
    private var mEndDate = ""

    override fun getViewModel() = get<MemberViewModel>()

    override fun initData() {
        initTitle(title = "消费记录")

        initLayout()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding.listLayout.apply {
            emptyLayout.also {
                it.emptyHint.text = "暂无相关消费记录！"
            }

            recycleList.also { layout ->
                layout.loadLinear(
                    refresh = swipeRefresh,
                    onRefresh = { getData(0) },
                    onLoad = {
                        if (!isLoadingMore) {
                            isLoadingMore = true
                            getData(pageNum)
                        }
                    }
                )

                mAdapter = SlimAdapter.creator()
                    .register<OrderHeader>(R.layout.item_order_list_title) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_order_time, bean.hint + bean.time)
                            text(R.id.item_order_status, bean.status_hint)
                            clicked {
                                startActivityEx<OrderDetailActivity>(
                                    "orderSn" to bean.orderSN
                                )
                            }
                        }
                    }
                    .register<OrderGoods>(R.layout.item_order_list_content) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_order_name, bean.name)
                            text(R.id.item_order_type, "规格：${bean.spec.orEmpty()}")
                            text(R.id.item_order_price, "单价：${bean.price.formatDecimal()}元")
                            text(R.id.item_order_num, "x${bean.quantity}")

                            visibility(
                                R.id.item_order_img_label,
                                visibleValue { bean.first }
                            )

                            with<ImageView>(R.id.item_order_img) {
                                it.loadImage(bean.thumbnail)
                            }

                            with<ImageView>(R.id.item_order_img_type) {
                                when (bean.methodDescr) {
                                    "offline" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order03)
                                    }

                                    "eleme", "elemengc" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order04)
                                    }

                                    "meituan" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order05)
                                    }

                                    "nongfu" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order06)
                                    }

                                    "jd" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order10)
                                    }

                                    "taobao" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order11)
                                    }

                                    "pinduoduo" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order12)
                                    }

                                    "dummy" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order22)
                                    }

                                    "ali" -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order26)
                                    }

                                    else -> it.gone()
                                }
                            }

                            with<ImageView>(R.id.item_order_img_status) {
                                when {
                                    bean.hopeDate.isNotEmpty() && !bean.fast -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order02)
                                    }

                                    bean.hopeDate.isNotEmpty() && bean.fast -> {
                                        it.visible()
                                        it.setImageResource(R.mipmap.icon_order07)
                                    }

                                    else -> it.gone()
                                }
                            }

                            clicked {
                                startActivityEx<OrderDetailActivity>(
                                    "orderSn" to bean.orderSN
                                )
                            }
                        }
                    }
                    .register<OrderFooter>(R.layout.item_order_list_foot) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_order_count, bean.total_num)
                            text(R.id.item_order_total, bean.amount.formatDecimal())
                            text(R.id.item_order_total_hint, bean.amountHint)
                            text(R.id.item_order_name, bean.name)
                            text(R.id.item_order_phone, bean.phone)
                            text(R.id.item_order_addr, bean.address)
                            text(R.id.item_order_cmemo, bean.cardMemo)
                            text(R.id.item_order_bmemo, bean.memo)

                            getView<View>(R.id.item_order_cmemo_ll)
                                .isGone = bean.cardMemo.isEmpty()
                            getView<View>(R.id.item_order_bmemo_ll)
                                .isGone = bean.memo.isEmpty()

                            with<TextView>(R.id.item_order_pei) { tv ->
                                tv.text =
                                    "配送员：${bean.adminName}${bean.adminPhone.ifNotEmpty { " - $it" }}"
                                tv.isGone = bean.adminName.isEmpty()
                            }

                            clicked {
                                startActivityEx<OrderDetailActivity>(
                                    "orderSn" to bean.orderSN
                                )
                            }
                        }
                    }
                    .attachTo(layout)
            }
        }
    }

    override fun initListener() {
        mDateMode = intent.getExtra("dateMode")
        mBeginDate = intent.getExtra("beginDate")
        mEndDate = intent.getExtra("endDate")

        // 今日、昨日、本周、本月、上月、本年、自定义
        mBinding.apply {
            when (mDateMode) {
                "1" -> {
                    recordTime.timeHint.text = "今日"
                    getViewModel().mUncheckTimeList[0].isChecked = true
                }

                "2" -> {
                    recordTime.timeHint.text = "昨日"
                    getViewModel().mUncheckTimeList[1].isChecked = true
                }

                "3" -> {
                    recordTime.timeHint.text = "本周"
                    getViewModel().mUncheckTimeList[2].isChecked = true
                }

                "5" -> {
                    recordTime.timeHint.text = "上月"
                    getViewModel().mUncheckTimeList[4].isChecked = true
                }

                "6" -> {
                    recordTime.timeHint.text = "本年"
                    getViewModel().mUncheckTimeList[5].isChecked = true
                }

                "7" -> {
                    recordTime.timeHint.text = "$mBeginDate ~ $mEndDate"
                    getViewModel().mUncheckTimeList[6].isChecked = true
                }

                else -> {
                    mBeginDate = getFirstDate()
                    mEndDate = getEndDate()

                    recordTime.timeHint.text = "本月"
                    getViewModel().mUncheckTimeList[3].isChecked = true
                }
            }
        }

        mBinding
            .recordTime
            .apply {
                timeLayout.oneClick {
                    getViewModel()
                        .showDropTimeFilter(
                            getIContext(),
                            timeHint,
                            timeHintArrow,
                            timeLayout,
                            getViewModel().mUncheckTimeList
                        ) { bean ->

                            if (bean.id != "7")
                                getViewModel()
                                    .mUncheckTimeList
                                    .last()
                                    .name = "自定义时间"

                            when (bean.id) {
                                "1" -> {
                                    mBeginDate = getTodayDate()
                                    mEndDate = getTodayDate()

                                    updateList()
                                }

                                "2" -> {
                                    mBeginDate = getBeforeDate()
                                    mEndDate = getBeforeDate()

                                    updateList()
                                }

                                "3" -> {
                                    mBeginDate = getMondayDate()
                                    mEndDate = getSundayDate()

                                    updateList()
                                }

                                "4" -> {
                                    mBeginDate = getFirstDate()
                                    mEndDate = getEndDate()

                                    updateList()
                                }

                                "5" -> {
                                    mBeginDate = getBeforeFirstDate()
                                    mEndDate = getBeforeEndDate()

                                    updateList()
                                }

                                "6" -> {
                                    mBeginDate = getYearFirstDate()
                                    mEndDate = getYearEndDate()

                                    updateList()
                                }

                                "7" -> {
                                    showTimeRangeDialog(
                                        isCurrentDate = true,
                                        isAfterLimited = true,
                                        onResult = { start, end ->
                                            getViewModel()
                                                .mUncheckTimeList
                                                .forEach { it.isChecked = false }

                                            getViewModel()
                                                .mUncheckTimeList
                                                .last()
                                                .isChecked = true

                                            mBeginDate = start
                                            mEndDate = end
                                            bean.name = "$mBeginDate ~ $mEndDate"
                                            timeHint.text = bean.name

                                            updateList()
                                        }
                                    )
                                }
                            }
                        }
                }
            }
    }

    /**
     * 消费记录列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .memberOrder(
                page = index,
                memberId = intent.getExtra("memberId"),
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    mList.apply {
                        if (index == 0) {
                            clear()
                            pageNum = 0
                        }
                        addItems(it)
                        if (it.count() > 0) pageNum++
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        if (mList.isNotEmpty()) {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}